<template>
  <div class="home-container">
    <!-- Welcome banner -->
    <div class="welcome-banner">
      <div class="banner-content">
        <h1>欢迎使用智能音箱管理系统</h1>
        <p>轻松管理音频设备、监控数据、分析诊断一站式解决方案</p>
        <el-button type="primary" size="large" @click="goToAnalysis">
          <el-icon><DataAnalysis /></el-icon> 查看数据分析
        </el-button>
      </div>
      <div class="banner-image">
        <img src="@/assets/dashboard-illustration.svg" alt="Dashboard" />
      </div>
    </div>

    <!-- Main dashboard content -->
    <div class="row-container">
      <el-row :gutter="30">
        <!-- Activity chart -->
        <el-col :span="24">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <div class="card-title-area">
                  <span class="card-title">用户/设备活跃曲线</span>
                  <el-tag size="small" effect="plain" type="info">{{ getTimeRangeLabel() }}</el-tag>
                </div>
                <div class="card-actions">
                  <el-radio-group v-model="timeRange" size="small" @change="handleTimeRangeChange">
                    <el-radio-button label="day">日</el-radio-button>
                    <el-radio-button label="week">周</el-radio-button>
                    <el-radio-button label="month">月</el-radio-button>
                  </el-radio-group>
                </div>
              </div>
            </template>
            <div class="chart-wrapper">
              <div ref="growthChart" class="chart-container"></div>
              <div v-if="loading" class="chart-loading">
                <el-icon><Loading /></el-icon>
                <span>加载中...</span>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    
    <!-- Status charts -->
    <div class="row-container">
      <el-row :gutter="30" class="middle-row">
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span class="card-title">设备状态分布</span>
              </div>
            </template>
            <div class="chart-wrapper">
              <div ref="statusChart" class="chart-container"></div>
              <div v-if="loading" class="chart-loading">
                <el-icon><Loading /></el-icon>
                <span>加载中...</span>
              </div>
            </div>
          </el-card>
        </el-col>
        
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span class="card-title">用户收听时段热力图</span>
              </div>
            </template>
            <div class="chart-wrapper">
              <div ref="heatmapChart" class="chart-container"></div>
              <div v-if="loading" class="chart-loading">
                <el-icon><Loading /></el-icon>
                <span>加载中...</span>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    
    <!-- Quick access and recent tasks -->
    <div class="row-container">
      <el-row :gutter="30" class="bottom-row">
        <el-col :span="12">
          <el-card class="quick-access-card">
            <template #header>
              <div class="card-header">
                <span class="card-title">快速访问</span>
              </div>
            </template>
            <div class="quick-access-grid">
              <div class="quick-access-item" v-for="(item, index) in quickAccess" :key="index" @click="navigateTo(item.path)">
                <div class="quick-access-icon">
                  <el-icon>
                    <component :is="item.icon" />
                  </el-icon>
                </div>
                <span>{{ item.name }}</span>
              </div>
            </div>
          </el-card>
        </el-col>
        
        <el-col :span="12">
          <el-card class="tasks-card">
            <template #header>
              <div class="card-header">
                <span class="card-title">用户反馈与待办</span>
                <el-button type="text" @click="refreshFeedback">刷新</el-button>
              </div>
            </template>
            <div class="tasks-list">
              <div v-if="loading" class="task-loading">
                <el-icon><Loading /></el-icon>
                <span>加载中...</span>
              </div>
              <div v-else-if="feedbackList.length === 0" class="no-tasks">
                <el-icon><ChatDotSquare /></el-icon>
                <span>暂无用户反馈</span>
              </div>
              <div class="task-item" v-for="item in feedbackList" :key="item.feedback_id">
                <el-checkbox v-model="item.isHandled" @change="handleFeedbackStatusChange(item)"></el-checkbox>
                <div class="task-content" :class="{ 'task-done': item.isHandled }">
                  <div class="task-title">{{ item.title }}</div>
                  <div class="task-description">{{ item.content }}</div>
                  <div class="task-meta">
                    <el-tag size="small" :type="getFeedbackTypeTag(item.type)">{{ item.type }}</el-tag>
                    <el-tag size="small" :type="getFeedbackStatusTag(item.status)">{{ item.status }}</el-tag>
                    <span class="task-due">{{ formatFeedbackTime(item.submit_time) }}</span>
                  </div>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    
    <!-- Page actions floats -->
    <div class="floating-actions">
      <el-button type="primary" @click="refreshData" :loading="loading" class="refresh-btn">
        <el-icon><RefreshRight /></el-icon>
      </el-button>
    </div>

    <!-- Bottom safe area -->
    <div class="bottom-safe-area"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import { debounce } from 'lodash';
import axios from 'axios';
import { 
  DataAnalysis, 
  RefreshRight, 
  Cpu, 
  Warning, 
  DataLine, 
  Timer, 
  Folder, 
  User, 
  Loading, 
  ChatDotSquare,
  Bell
} from '@element-plus/icons-vue'

export default {
  name: 'HomePage',
  components: {
    DataAnalysis,
    RefreshRight,
    Cpu,
    Warning,
    DataLine,
    Timer,
    Folder,
    User,
    Loading,
    ChatDotSquare,
    Bell
  },
  data() {
    return {
      loading: false,
      feedbackLoading: false,
      autoRefresh: false,
      refreshTimer: null,
      timeRange: 'week', // 默认使用周视图
      charts: {
        growthChart: null,
        heatmapChart: null,
        statusChart: null
      },
      resizeHandler: null,
      
      // User and device activity data
      userActivityData: null,
      deviceActivityData: null,
      
      // Feedback data
      feedbackList: [],
      
      recentAlerts: [
        { id: 1, level: 'danger', title: '设备离线告警', device: 'Device-001', time: '10分钟前' },
        { id: 2, level: 'warning', title: '温度超限告警', device: 'Device-002', time: '30分钟前' },
        { id: 3, level: 'info', title: '连接异常告警', device: 'Device-003', time: '1小时前' },
        { id: 4, level: 'warning', title: '电量不足告警', device: 'Device-004', time: '2小时前' }
      ],
      
      quickAccess: [
        { name: '设备管理', path: '/device', icon: 'Cpu' },
        { name: '反馈中心', path: '/feedback', icon: 'ChatDotSquare' },
        { name: '数据分析', path: '/analysis', icon: 'DataLine' },
        { name: '公告运营', path: '/content', icon: 'Bell' },
        { name: '资源库', path: '/resource', icon: 'Folder' },
        { name: '用户管理', path: '/user', icon: 'User' }
      ]
    }
  },
  mounted() {
    // 先初始化图表结构
    this.initCharts();
    
    // 立即加载数据
    this.loadData();
    
    // 加载反馈数据
    this.loadFeedbackData();
    
    // 使用防抖函数处理窗口大小变化
    this.resizeHandler = debounce(this.resizeCharts, 300);
    window.addEventListener('resize', this.resizeHandler);
    
    // 在组件挂载后添加延迟重新调整图表大小的处理
    this.$nextTick(() => {
      setTimeout(() => {
        this.resizeCharts();
      }, 500);
    });
  },
  beforeUnmount() {
    // 清除定时器和事件监听器
    if (this.refreshTimer) {
      clearInterval(this.refreshTimer);
    }
    window.removeEventListener('resize', this.resizeHandler);
    
    // 销毁图表实例
    Object.values(this.charts).forEach(chart => {
      if (chart) {
        chart.dispose();
      }
    });
  },
  methods: {
    goToAnalysis() {
      this.$router.push('/analysis');
    },
    handleAlert(alert) {
      // 处理告警的逻辑
      this.$message.success(`正在处理告警: ${alert.title}`);
    },
    navigateTo(path) {
      this.$router.push(path);
    },
    createTask() {
      // 创建新任务的逻辑
      this.$message.info('打开新建任务对话框');
    },
    taskStatusChanged(task) {
      // 任务状态变更的逻辑
      const status = task.done ? '完成' : '恢复';
      this.$message.success(`任务"${task.title}"已${status}`);
    },
    getPriorityLabel(priority) {
      const labels = {
        'danger': '紧急',
        'warning': '重要',
        'primary': '中等',
        'info': '普通'
      };
      return labels[priority] || priority;
    },
    
    // Charts methods
    initCharts() {
      this.initGrowthChart();
      this.initHeatmapChart();
      this.initStatusChart();
      this.loadData();
    },
    
    initGrowthChart() {
      const chartDom = this.$refs.growthChart;
      this.charts.growthChart = echarts.init(chartDom);
      
      // 设置基本配置，但不包含数据
      const option = {
        tooltip: {
          trigger: 'axis',
          backgroundColor: 'rgba(255, 255, 255, 0.9)',
          borderColor: '#f0f0f0',
          borderWidth: 1,
          textStyle: {
            color: '#333'
          },
          axisPointer: {
            type: 'shadow',
            shadowStyle: {
              color: 'rgba(24, 144, 255, 0.05)'
            }
          }
        },
        legend: {
          data: ['用户活跃度', '设备活跃度'],
          right: '4%',
          textStyle: {
            color: '#606266'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: [],
          axisLine: {
            lineStyle: {
              color: '#ddd'
            }
          },
          axisTick: {
            alignWithLabel: true
          }
        },
        yAxis: {
          type: 'value',
          name: '活跃数',
          splitLine: {
            lineStyle: {
              type: 'dashed',
              color: '#eee'
            }
          },
          axisLine: {
            lineStyle: {
              color: '#ddd'
            }
          }
        },
        series: [
          {
            name: '用户活跃度',
            type: 'line',
            smooth: true,
            data: [],
            itemStyle: {
              color: '#1890ff'
            },
            lineStyle: {
              width: 3,
              shadowColor: 'rgba(24, 144, 255, 0.3)',
              shadowBlur: 10,
              shadowOffsetY: 8
            },
            areaStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [{
                  offset: 0, color: 'rgba(24, 144, 255, 0.3)'
                }, {
                  offset: 1, color: 'rgba(24, 144, 255, 0.05)'
                }]
              }
            }
          },
          {
            name: '设备活跃度',
            type: 'line',
            smooth: true,
            data: [],
            itemStyle: {
              color: '#52c41a'
            },
            lineStyle: {
              width: 3,
              shadowColor: 'rgba(82, 196, 26, 0.3)',
              shadowBlur: 10,
              shadowOffsetY: 8
            },
            areaStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [{
                  offset: 0, color: 'rgba(82, 196, 26, 0.3)'
                }, {
                  offset: 1, color: 'rgba(82, 196, 26, 0.05)'
                }]
              }
            }
          },

        ]
      };
      
      this.charts.growthChart.setOption(option);
    },
    
    initHeatmapChart() {
      const chartDom = this.$refs.heatmapChart;
      this.charts.heatmapChart = echarts.init(chartDom);
      
      // 设置基本配置，但不包含数据
      const option = {
        tooltip: {
          position: 'top',
          formatter: function (params) {
            const weekdays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
            const weekday = weekdays[params.data[1]];
            const hour = params.data[0] + ':00';
            return `${weekday} ${hour}<br/>播放次数: ${params.data[2]}`;
          },
          backgroundColor: 'rgba(255, 255, 255, 0.9)',
          borderColor: '#f0f0f0',
          borderWidth: 1,
          textStyle: {
            color: '#333'
          }
        },
        grid: {
          top: 60,
          left: '3%',
          right: '4%',
          bottom: 60,
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: [],
          splitArea: {
            show: true
          },
          axisLine: {
            lineStyle: {
              color: '#ddd'
            }
          },
          axisTick: {
            alignWithLabel: true
          },
          name: '小时',
          nameLocation: 'middle',
          nameGap: 40
        },
        yAxis: {
          type: 'category',
          data: [],
          splitArea: {
            show: true
          },
          axisLine: {
            lineStyle: {
              color: '#ddd'
            }
          },
          axisTick: {
            alignWithLabel: true
          },
          nameLocation: 'end',
          nameGap: 15
        },
        visualMap: {
          min: 0,
          max: 10,
          calculable: true,
          orient: 'horizontal',
          left: 'center',
          bottom: 10,
          inRange: {
            color: ['#ecf5ff', '#409eff', '#1890ff', '#005cc8']
          },
          text: ['高', '低'],
          dimension: 2
        },
        series: [{
          name: '时间活跃度',
          type: 'heatmap',
          data: [],
          label: {
            show: false
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }]
      };
      
      this.charts.heatmapChart.setOption(option);
    },
    
    initStatusChart() {
      const chartDom = this.$refs.statusChart;
      this.charts.statusChart = echarts.init(chartDom);
      
      // 设置基本配置，但不包含数据
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)',
          backgroundColor: 'rgba(255, 255, 255, 0.9)',
          borderColor: '#f0f0f0',
          borderWidth: 1,
          textStyle: {
            color: '#333'
          }
        },
        legend: {
          orient: 'vertical',
          right: 10,
          top: 'center',
          data: [],
          textStyle: {
            color: '#606266'
          },
          itemWidth: 10,
          itemHeight: 10,
          itemGap: 15
        },
        series: [
          {
            name: '设备状态',
            type: 'pie',
            radius: ['55%', '75%'],
            center: ['45%', '50%'],
            avoidLabelOverlap: false,
            label: {
              show: true,
              position: 'outside',
              formatter: '{b}: {c}台',
              fontSize: 14
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 16,
                fontWeight: 'bold'
              },
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.2)'
              }
            },
            labelLine: {
              show: true,
              length: 15,
              length2: 10
            },
            itemStyle: {
              borderRadius: 5,
              borderWidth: 2,
              borderColor: '#fff'
            },
            data: []
          }
        ]
      };
      
      this.charts.statusChart.setOption(option);
    },
    
    loadData() {
      this.loading = true;
      
      // 获取用户和设备活跃度数据
      const daysParam = this.getDaysParam();
      
      // 并行请求用户和设备活跃度数据
      Promise.all([
        axios.get(`https://smartsound.top/api/v1/admin/user_activity?days=${daysParam}`),
        axios.get(`https://smartsound.top/api/v1/admin/device_activity?days=${daysParam}`)
      ])
      .then(([userResponse, deviceResponse]) => {
        this.userActivityData = userResponse.data.data;
        this.deviceActivityData = deviceResponse.data.data;
        
        // 更新用户/设备活跃曲线图表
        this.updateGrowthChart();
        
        this.loading = false;
      })
      .catch(error => {
        console.error('获取数据失败：', error);
        this.$message.error('获取活跃度数据失败，请稍后重试');
        this.loading = false;
      });
      
      // 设备状态图表单独更新（使用不同的API）
      this.updateStatusChart();
      
      // 时间热力图单独更新（使用不同的API）
      this.updateHeatmapChart();
    },
    
    getDaysParam() {
      // 根据时间范围返回对应的天数
      switch(this.timeRange) {
        case 'day':
          return 7;  // 一周的数据
        case 'week':
          return 30; // 30天的数据
        case 'month':
          return 100; // 显示所有月数据
        default:
          return 30;
      }
    },
    
    updateGrowthChart() {
      if (!this.userActivityData || !this.deviceActivityData) {
        return;
      }
      
      // 处理数据以适应图表
      let dates = [];
      let userActivity = [];
      let deviceActivity = [];
      
      // 根据时间范围选择适当的数据源
      let userDataSource, deviceDataSource;
      
      // 定义可能在case内部使用的变量
      let recentWeeks, startIndex;
      
      switch(this.timeRange) {
        case 'day':
          // 日视图 - 使用日期（从旧到新排序）
          userDataSource = this.userActivityData.daily_activity.slice(0, 7);
          deviceDataSource = this.deviceActivityData.daily_activity.slice(0, 7);
          // 提取日视图数据 - 保持从旧到新的顺序
          dates = userDataSource.map(item => item.date);
          userActivity = userDataSource.map(item => item.active_users);
          deviceActivity = deviceDataSource.map(item => item.active_devices);
          break;
        case 'week':
          // 周视图 - 使用API返回的周数据，但仅显示最近覆盖30天的周数据
          userDataSource = this.userActivityData.weekly_summary;
          deviceDataSource = this.deviceActivityData.weekly_summary;
          
          // 如果有完整的周数据，只取最后4个周（约30天）
          recentWeeks = 4; // 4周近似30天
          startIndex = Math.max(0, userDataSource.length - recentWeeks);
          userDataSource = userDataSource.slice(startIndex);
          deviceDataSource = deviceDataSource.slice(startIndex);
          
          dates = userDataSource.map(item => {
            // 针对格式 "第X周 (YYYY-MM-DD to YYYY-MM-DD)" 进行解析
            const weekRegex = /第\d+周\s+\((\d{4}-\d{2}-\d{2})\s+to\s+\d{4}-\d{2}-\d{2}\)/;
            const match = item.week.match(weekRegex);
            
            if (match && match[1]) {
              // 提取第一个日期 (每周的第一天)
              const firstDayDate = match[1];
              try {
                const date = new Date(firstDayDate);
                if (!isNaN(date.getTime())) {
                  // 格式化为MM-DD格式
                  const month = (date.getMonth() + 1).toString().padStart(2, '0');
                  const day = date.getDate().toString().padStart(2, '0');
                  return `${month}-${day}`;
                }
              } catch (e) {
                console.error('日期解析错误:', firstDayDate, e);
              }
            }
            
            // 如果无法提取日期，返回原始周标签的第一部分 (如 "第1周")
            const weekLabel = item.week.split(' ')[0];
            return weekLabel;
          });
          
          userActivity = userDataSource.map(item => item.active_users);
          deviceActivity = deviceDataSource.map(item => item.active_devices);
          break;
        case 'month':
          // 月视图 - 使用月份
          userDataSource = this.userActivityData.monthly_summary;
          deviceDataSource = this.deviceActivityData.monthly_summary;
          dates = userDataSource.map(item => item.month);
          userActivity = userDataSource.map(item => item.active_users);
          deviceActivity = deviceDataSource.map(item => item.active_devices);
          break;
        default:
          userDataSource = this.userActivityData.daily_activity;
          deviceDataSource = this.deviceActivityData.daily_activity;
          // 默认使用日视图数据提取方式
          dates = userDataSource.map(item => item.date);
          userActivity = userDataSource.map(item => item.active_users);
          deviceActivity = deviceDataSource.map(item => item.active_devices);
      }
      
      // 更新图表
      this.charts.growthChart.setOption({
        xAxis: {
          data: dates
        },
        series: [
          {
            name: '用户活跃度',
            data: userActivity
          },
          {
            name: '设备活跃度',
            data: deviceActivity
          }
        ]
      });
    },
    
    updateHeatmapChart() {
      // 从API获取听歌时段分布数据
      const daysParam = this.getDaysParam();
      axios.get(`https://smartsound.top/api/v1/admin/listening_time_distribution?days=${daysParam}`)
        .then(response => {
          if (response.data.code === 0) {
            const distributionData = response.data.data;
            const weekdayHourly = distributionData.weekday_hourly_distribution || [];

            // x轴：小时
            const hours = Array.from({ length: 24 }, (_, i) => `${i}:00`);
            // y轴：星期
            const weekdays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];

            // 构建热力图数据
            const data = [];
            let maxValue = 0;

            // weekday: 0=周一, 6=周日
            for (let i = 0; i < weekdayHourly.length; i++) {
              const day = weekdayHourly[i];
              for (let j = 0; j < day.hourly_data.length; j++) {
                const hourData = day.hourly_data[j];
                const value = hourData.play_count;
                if (value > maxValue) maxValue = value;
                data.push([hourData.hour, day.weekday, value]);
              }
            }

            this.charts.heatmapChart.setOption({
              tooltip: {
                position: 'top',
                formatter: function (params) {
                  const weekdays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
                  const weekday = weekdays[params.data[1]];
                  const hour = params.data[0] + ':00';
                  return `${weekday} ${hour}<br/>播放次数: ${params.data[2]}`;
                },
                backgroundColor: 'rgba(255, 255, 255, 0.9)',
                borderColor: '#f0f0f0',
                borderWidth: 1,
                textStyle: {
                  color: '#333'
                }
              },
              xAxis: {
                type: 'category',
                data: hours
              },
              yAxis: {
                type: 'category',
                data: weekdays
              },
              visualMap: {
                min: 0,
                max: maxValue > 0 ? maxValue : 10,
                calculable: true,
                orient: 'horizontal',
                left: 'center',
                bottom: 10,
                inRange: {
                  color: ['#ecf5ff', '#409eff', '#1890ff', '#005cc8']
                },
                text: ['高', '低'],
                seriesIndex: 0
              },
              series: [{
                name: '时间活跃度',
                type: 'heatmap',
                data: data,
                label: {
                  show: false
                },
                emphasis: {
                  itemStyle: {
                    shadowBlur: 10,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                  }
                }
              }]
            });
          }
        })
        .catch(error => {
          console.error('获取听歌时段分布数据失败：', error);
        });
    },
    
    updateStatusChart() {
      // 从API获取设备状态数据
      axios.get('https://smartsound.top/api/v1/admin/devices/status?size=10&page=1')
        .then(response => {
          if (response.data.code === 0) {
            const statusData = response.data.data;
            
            // 使用新的API返回格式创建饼图数据
            const chartData = [
              { value: statusData.online, name: '在线', itemStyle: { color: '#52c41a' } },
              { value: statusData.offline, name: '离线', itemStyle: { color: '#bfbfbf' } },
              { value: statusData.inactive, name: '未激活', itemStyle: { color: '#faad14' } },
            ];
            
            // 过滤掉数量为0的状态
            const filteredStatusData = chartData.filter(item => item.value > 0);
            
            // 更新图表
            this.charts.statusChart.setOption({
              legend: {
                data: filteredStatusData.map(item => item.name)
              },
              series: [
                {
                  name: '设备状态',
                  type: 'pie',
                  radius: ['55%', '75%'],
                  center: ['45%', '50%'],
                  avoidLabelOverlap: false,
                  data: filteredStatusData,
                  // 根据数据量调整标签显示方式
                  label: {
                    show: true,
                    formatter: filteredStatusData.length > 5 ? '{b}' : '{b}: {c}台'
                  }
                }
              ]
            });
          }
        })
        .catch(error => {
          console.error('获取设备状态数据失败：', error);
        });
    },
    
    handleTimeRangeChange() {
      this.loadData();
    },
    
    getTimeRangeLabel() {
      switch(this.timeRange) {
        case 'day':
          return '过去7天';
        case 'week':
          return '最近30天';
        case 'month':
          return '过去100天';
        default:
          return '过去30天';
      }
    },
    
    refreshData() {
      this.loadData();
    },
    
    resizeCharts() {
      Object.values(this.charts).forEach(chart => {
        if (chart) {
          chart.resize();
        }
      });
      
      // 解决echarts渲染问题
      this.$nextTick(() => {
        Object.values(this.charts).forEach(chart => {
          if (chart) {
            chart.resize();
          }
        });
      });
    },
    
    handleAutoRefreshChange(value) {
      if (value) {
        this.refreshTimer = setInterval(() => {
          this.refreshData();
          this.refreshFeedback();
        }, 30000); // 30秒刷新一次
      } else if (this.refreshTimer) {
        clearInterval(this.refreshTimer);
      }
    },
    
    refreshFeedback() {
      this.loadFeedbackData();
    },
    
    loadFeedbackData() {
      this.feedbackLoading = true;
      
      axios.get('https://smartsound.top/api/admin/feedback/v1/list?status=&type=&page=1&page_size=10')
        .then(response => {
          if (response.data.code === 0) {
            // 处理获取到的反馈数据
            const feedbackData = response.data.feedback_list || [];
            
            // 转换为任务格式
            this.feedbackList = feedbackData.map(item => ({
              ...item,
              isHandled: item.status === '已处理' || item.status === '已回复'
            }));
          } else {
            this.$message.error('获取反馈数据失败：' + response.data.message);
          }
          this.feedbackLoading = false;
        })
        .catch(error => {
          console.error('获取反馈数据失败：', error);
          this.$message.error('获取反馈数据失败，请稍后重试');
          this.feedbackLoading = false;
        });
    },
    
    handleFeedbackStatusChange(feedback) {
      const newStatus = feedback.isHandled ? '已处理' : '待处理';
      this.$message.success(`反馈"${feedback.title}"状态已更新为${newStatus}`);
      
      // 实际场景中这里应该调用更新状态的API
      // axios.post('https://smartsound.top/api/admin/feedback/v1/update', {
      //   feedback_id: feedback.feedback_id,
      //   status: newStatus
      // })
    },
    
    getFeedbackTypeTag(type) {
      const typeMap = {
        'BUG': 'danger',
        '建议': 'primary',
        '咨询': 'info',
        '其他': 'warning'
      };
      return typeMap[type] || 'info';
    },
    
    getFeedbackStatusTag(status) {
      const statusMap = {
        '待处理': 'warning',
        '处理中': 'primary',
        '已处理': 'success',
        '已回复': 'success',
        '已关闭': 'info'
      };
      return statusMap[status] || 'info';
    },
    
    formatFeedbackTime(timeString) {
      if (!timeString) return '';
      
      // 转换时间格式
      const date = new Date(timeString);
      const now = new Date();
      const diffMs = now - date;
      const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
      
      if (diffDays === 0) {
        // 今天
        return '今天 ' + date.getHours().toString().padStart(2, '0') + ':' + 
               date.getMinutes().toString().padStart(2, '0');
      } else if (diffDays === 1) {
        // 昨天
        return '昨天';
      } else if (diffDays < 7) {
        // 一周内
        return `${diffDays}天前`;
      } else {
        // 超过一周
        return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
      }
    },
  }
}
</script>

<style scoped>
/* 全局基础样式 */
.home-container {
  padding: 16px 5px;
  position: relative;
  margin-bottom: 80px; /* 进一步增加底部空间，避免与悬浮按钮冲突 */
}

/* 欢迎横幅调整 */
.welcome-banner {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: linear-gradient(135deg, #1890ff, #722ed1);
  color: white;
  border-radius: 12px;
  padding: 32px 40px;
  margin-bottom: 35px; /* 增加与图表的间距 */
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  position: relative;
}

.welcome-banner::after {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 50%;
  background: rgba(255, 255, 255, 0.1);
  transform: skewX(-20deg);
}

.banner-content {
  z-index: 1;
  max-width: 60%;
}

.banner-content h1 {
  font-size: 28px;
  margin: 0 0 12px 0;
  font-weight: 600;
}

.banner-content p {
  font-size: 16px;
  margin: 0 0 24px 0;
  opacity: 0.9;
  line-height: 1.6;
}

.banner-image {
  z-index: 1;
  max-width: 35%;
}

.banner-image img {
  max-width: 100%;
  height: auto;
}

/* 图表卡片样式调整 */
.chart-card, .alert-card, .quick-access-card, .tasks-card {
  height: 100%;
  margin-bottom: 30px; /* 统一所有卡片底部间距 */
  overflow: hidden;
  position: relative;
  display: flex;
  flex-direction: column;
  border-radius: 10px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  border: 1px solid rgba(0, 0, 0, 0.03);
  transform: translate3d(0, 0, 0); /* 强制开启硬件加速，避免重叠 */
  will-change: transform; /* 优化性能 */
}

.chart-card:hover, .alert-card:hover, .quick-access-card:hover, .tasks-card:hover {
  box-shadow: 0 8px 15px rgba(0, 0, 0, 0.08);
  transform: translateY(-2px);
  z-index: 1; /* 确保悬浮时不会被其他元素覆盖 */
  border-color: rgba(24, 144, 255, 0.1);
}

/* 行容器样式 */
.row-container {
  margin-bottom: 30px;
  position: relative;
  z-index: 0;
}

/* 修改el-row和el-col样式，确保固定间距 */
.el-row {
  display: flex;
  flex-wrap: wrap;
  margin-right: -15px !important;
  margin-left: -15px !important;
}

.el-col {
  padding-right: 15px !important;
  padding-left: 15px !important;
  margin-bottom: 30px;
}

/* 修复每行等高布局 */
.middle-row, .bottom-row {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 0; /* 移除行间距，由列元素控制 */
}

.middle-row > .el-col, .bottom-row > .el-col {
  display: flex;
  flex-direction: column;
}

/* 设置不同分辨率下的间距 */
@media (min-width: 1200px) {
  .el-row {
    margin-right: -20px !important;
    margin-left: -20px !important;
  }
  
  .el-col {
    padding-right: 20px !important;
    padding-left: 20px !important;
  }
}

@media (max-width: 768px) {
  .el-row {
    margin-right: -10px !important;
    margin-left: -10px !important;
  }
  
  .el-col {
    padding-right: 10px !important;
    padding-left: 10px !important;
    margin-bottom: 20px;
  }
}

.el-card__body {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px; /* 调整卡片头部内边距 */
}

.card-title-area {
  display: flex;
  align-items: center;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  margin-right: 12px;
}

.chart-wrapper {
  position: relative;
  height: 300px;
  width: 100%;
  flex: 1;
}

.chart-container {
  height: 100%;
  width: 100%;
}

.chart-loading {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: rgba(255, 255, 255, 0.7);
  z-index: 2;
}

.chart-loading i {
  font-size: 24px;
  color: #1890ff;
  margin-bottom: 8px;
}

/* 告警列表 */
.alert-list {
  max-height: 300px;
  overflow-y: auto;
  flex: 1;
}

.alert-item {
  display: flex;
  align-items: center;
  padding: 12px 16px; /* 调整内边距 */
  border-bottom: 1px solid #f0f0f0;
  transition: all 0.3s;
}

.alert-item:last-child {
  border-bottom: none;
}

.alert-item:hover {
  background-color: #f9f9f9;
  transform: translateX(5px);
}

.alert-icon {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-right: 12px;
  flex-shrink: 0; /* 防止图标被挤压 */
}

.alert-critical {
  background-color: #f5222d;
  box-shadow: 0 0 10px rgba(245, 34, 45, 0.5);
}

.alert-danger {
  background-color: #f5222d;
  box-shadow: 0 0 10px rgba(245, 34, 45, 0.5);
}

.alert-warning {
  background-color: #faad14;
  box-shadow: 0 0 10px rgba(250, 173, 20, 0.5);
}

.alert-info {
  background-color: #1890ff;
  box-shadow: 0 0 10px rgba(24, 144, 255, 0.5);
}

.alert-content {
  flex: 1;
  min-width: 0; /* 确保文本可以在空间不足时正常换行 */
}

.alert-title {
  font-weight: 500;
  margin-bottom: 4px;
  color: #303133;
}

.alert-info {
  color: #909399;
  font-size: 12px;
}

.alert-action {
  margin-left: 8px;
  opacity: 0;
  transition: opacity 0.3s;
  flex-shrink: 0; /* 防止按钮被挤压 */
  white-space: nowrap; /* 按钮文本不换行 */
}

.alert-item:hover .alert-action {
  opacity: 1;
}

/* 快速访问网格 */
.quick-access-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
  padding: 8px; /* 增加内边距 */
}

.quick-access-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 16px;
  border-radius: 8px;
  transition: all 0.3s;
  cursor: pointer;
  text-align: center;
}

.quick-access-item:hover {
  background-color: #f0f7ff;
  transform: translateY(-5px);
  z-index: 1; /* 确保悬浮时不会被其他元素覆盖 */
}

.quick-access-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 48px;
  height: 48px;
  border-radius: 12px;
  margin-bottom: 12px;
  background: linear-gradient(135deg, #1890ff, #722ed1);
  color: white;
  transition: all 0.3s;
}

.quick-access-item:hover .quick-access-icon {
  transform: scale(1.1);
}

.quick-access-icon i {
  font-size: 24px;
}

/* 任务列表 */
.tasks-list {
  max-height: 300px; /* 增加高度以匹配其他卡片 */
  overflow-y: auto;
  flex: 1;
  padding: 4px 8px; /* 增加内边距 */
}

.task-loading, .no-tasks {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
  color: #909399;
}

.task-loading i, .no-tasks i {
  font-size: 32px;
  margin-bottom: 12px;
}

.task-item {
  display: flex;
  align-items: flex-start;
  padding: 12px 8px; /* 调整内边距 */
  border-bottom: 1px solid #f0f0f0;
  transition: background-color 0.3s;
}

.task-item:last-child {
  border-bottom: none;
}

.task-item:hover {
  background-color: #f9f9f9;
}

.task-content {
  flex: 1;
  margin-left: 12px;
  min-width: 0; /* 确保文本可以在空间不足时正常换行 */
}

.task-title {
  font-weight: 500;
  margin-bottom: 6px;
  transition: all 0.3s;
}

.task-description {
  font-size: 13px;
  color: #606266;
  margin-bottom: 8px;
  line-height: 1.5;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.task-done .task-title {
  color: #909399;
  text-decoration: line-through;
}

.task-done .task-description {
  color: #c0c4cc;
}

.task-meta {
  display: flex;
  align-items: center;
  flex-wrap: wrap; /* 允许在空间不足时换行 */
}

.task-meta .el-tag + .el-tag {
  margin-left: 8px;
}

.task-due {
  margin-left: 8px;
  font-size: 12px;
  color: #909399;
}

/* 调整浮动操作区域样式 */
.floating-actions {
  position: fixed;
  right: 24px;
  bottom: 24px;
  display: flex;
  align-items: center;
  z-index: 100; /* 提高悬浮按钮的层级，确保显示在最上层 */
}

.refresh-btn {
  margin-left: 16px;
  border-radius: 50%;
  width: 52px;
  height: 52px;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(45deg, #1890ff, #40a9ff);
  border-color: transparent;
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.4);
  transition: all 0.3s;
}

.refresh-btn:hover {
  transform: translateY(-5px) scale(1.05);
  box-shadow: 0 6px 16px rgba(24, 144, 255, 0.5);
}

.refresh-btn .el-icon {
  font-size: 24px;
  margin-right: 0;
}

/* 响应式调整优化 */
@media (max-width: 768px) {
  .el-row {
    margin-left: -10px !important;
    margin-right: -10px !important;
  }

  .el-col {
    padding-left: 10px !important;
    padding-right: 10px !important;
  }

  .welcome-banner {
    flex-direction: column;
    padding: 24px;
  }
  
  .banner-content {
    max-width: 100%;
    margin-bottom: 24px;
  }
  
  .banner-image {
    max-width: 80%;
  }
  
  .quick-access-grid {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .floating-actions {
    right: 16px;
    bottom: 16px;
  }

  .home-container {
    margin-bottom: 100px;
  }
  
  .bottom-safe-area {
    height: 80px;
  }
}

@media (max-width: 576px) {
  .stat-card {
    padding: 16px;
    margin-bottom: 12px;
  }
  
  .stat-icon {
    width: 40px;
    height: 40px;
  }
  
  .stat-number {
    font-size: 20px;
  }
  
  .chart-container {
    height: 250px;
  }
  
  .quick-access-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 8px;
  }
  
  .quick-access-icon {
    width: 40px;
    height: 40px;
  }
}

/* Bottom safe area */
.bottom-safe-area {
  height: 60px;
  width: 100%;
  margin-top: 20px;
}

/* 确保统计卡片行内组件均匀分布 */
.stats-section .el-row {
  justify-content: space-between;
}

.stats-section .el-col {
  margin-bottom: 20px;
  display: flex;
}

.row-container {
  margin-bottom: 30px;
  position: relative;
  z-index: 0;
}

.el-card {
  margin-bottom: 0 !important; /* 覆盖原有的margin-bottom */
}

.el-col {
  margin-bottom: 0 !important; /* 覆盖原有的margin-bottom，由row-container控制 */
}

/* 增强行容器样式 */
.row-container {
  margin-bottom: 30px;
  position: relative;
  z-index: 0;
  clear: both;
  overflow: visible;
}

/* 确保每行卡片间间距固定 */
.el-row {
  display: flex;
  flex-wrap: wrap;
  margin-right: -15px !important;
  margin-left: -15px !important;
  box-sizing: border-box;
}

/* 确保列元素间距固定 */
.el-col {
  padding-right: 15px !important;
  padding-left: 15px !important;
  margin-bottom: 0 !important;
  float: none !important;
  box-sizing: border-box;
}

/* 让每个卡片容器占满整个列空间 */
.el-card {
  width: 100%;
  height: 100%;
  margin-bottom: 0 !important;
  box-sizing: border-box;
  position: relative;
}

/* 卡片内容布局 */
.el-card__body {
  height: 100%;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
}

/* 修正布局重叠问题 */
.middle-row, .bottom-row {
  clear: both;
}

/* 设置统计卡片特定样式 */
.stats-section .el-row {
  justify-content: space-between;
}

.stats-section .el-col {
  display: flex;
}

/* 卡片间距在不同屏幕大小下的一致性 */
@media (min-width: 1200px) {
  .el-row {
    margin-right: -20px !important;
    margin-left: -20px !important;
  }
  
  .el-col {
    padding-right: 20px !important;
    padding-left: 20px !important;
  }
}

@media (max-width: 768px) {
  .el-row {
    margin-right: -10px !important;
    margin-left: -10px !important;
  }
  
  .el-col {
    padding-right: 10px !important;
    padding-left: 10px !important;
  }
  
  .row-container {
    margin-bottom: 20px;
  }
}
</style>